package com.soundplus.app.shp04.Activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.sppmode.Common.AllParam;
import com.example.sppmode.Common.PairedDeviceInfo;
import com.soundplus.app.shp04.Common.DeviceListAdapter;
import com.soundplus.app.shp04.R;
import com.soundplus.app.shp04.databinding.ActivityPairedDeviceListBinding;

import java.util.List;

public class PairedDevListActivity extends AppCompatActivity {

    private Context context;
    private ActivityPairedDeviceListBinding binding;
    private List<PairedDeviceInfo> pairedDevList;
    private DeviceListAdapter deviceListAdapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        context = this;
        binding = ActivityPairedDeviceListBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        initView();
    }

    private void initView() {
        pairedDevList = AllParam.getPairedDevInfo().getPairedDevList();
        deviceListAdapter = new DeviceListAdapter(context, pairedDevList);
        binding.lvDeviceList.setAdapter(deviceListAdapter);
        binding.lvDeviceList.setOnItemClickListener((adapterView, view, i, l) -> showAlertDialog(pairedDevList.get(i)));
    }

    private Dialog dialog;

    private void showAlertDialog(final PairedDeviceInfo pairedDeviceInfo) {
        dialog = new AlertDialog.Builder(context).
                setTitle(R.string.select_dev).
                setMessage(context.getString(R.string.connect) + " " + pairedDeviceInfo.getName()).
                setNegativeButton(R.string.cancel, (dialogInterface, i) -> dialog.dismiss()).
                setPositiveButton(R.string.connect, (dialogInterface, i) -> {
                    dialog.dismiss();

                    AllParam.getPairedDevInfo().updateLastConnDevInfo(pairedDeviceInfo, true);

                    Intent intent = new Intent(context, MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }).
                create();
        dialog.show();
    }
}
